package cn.alise.controller.user;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.xml.security.utils.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.alise.consts.ConfigConsts;
import cn.alise.controller.common.BaseController;
import cn.alise.qdp.model.common.Pagination;
import cn.alise.qdp.model.user.User;
import cn.alise.qdp.model.user.UserRole;
import cn.alise.qdp.service.common.UploadService;
import cn.alise.qdp.service.user.UserRoleService;
import cn.alise.qdp.service.user.UserService;
import cn.alise.util.JSONResult;
import cn.alise.util.Md5;


/**
 * 用户管理控制器
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

	private static final long serialVersionUID = 3071751434812887748L;
	private static final String ERROR_TITLE = "_error";
	private static final String REDIRECT_LIST = "redirect:list";
	
	@Resource(name = "userService")
	private UserService userService;
	
	@Resource(name = "userRoleService")
	private UserRoleService userRoleService;
	
	/**
	 * 上传图片服务类
	 */
	@Resource(name = "uploadService")
	private UploadService uploadService;

	/**
	 * 用户列表
	 */
	@RequestMapping(value = "/list")
	public String list(HttpServletRequest request, Model model,
			User args, Pagination page) {
		
		//session 获取organId
		String organId = this.getAccountFromSession().getOrganId();
				
		HashMap<String, Object> params = new HashMap<String, Object>();
		
		if(args.getOrganId()!=null && !"".equals(args.getOrganId())) {
			args.setOrganId(args.getOrganId());// 机构
		} else {
			args.setOrganId(organId);// 机构
		}
		
		// 查询用户记录总行数
		int total = this.userService.querytotal(args);
		if (total > 0) {
			
			page.setTotalCount(total);
			params.put("pageSize",    String.valueOf(page.getRowsPerPage()));
			params.put("currentPage", String.valueOf(page.getCurrentPage()));
			
			//分页查询用户列表
			if(args.getUserId() != null) {
				params.put("userId",    args.getUserId().toString());
			}
			params.put("userName",  args.getUserName());
			params.put("organId",  args.getOrganId());
			params.put("account",  args.getAccount());
			if(args.getStatus() != null) {
				params.put("status",  args.getStatus().toString());
			}
			
			// 设置分页信息
			params.put("start", (page.getCurrentPage() - 1) * page.getRowsPerPage());
			params.put("size",  page.getRowsPerPage());
			
			List<User> list = this.userService.querypage(params);
			if (!CollectionUtils.isEmpty(list)) {
				model.addAttribute("list", list);
			} else {
				model.addAttribute("list", ListUtils.EMPTY_LIST);
			}
		}
		
		model.addAttribute("user", args);
		model.addAttribute("pagination", page);	
		
		return "pages/user/user-list";
	}
	
	/**
	 * 跳转到用户创建页面
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(HttpServletRequest request, Model model) {
		
		return "pages/user/user-new";
	}
	
	/**
	 * ajax用户相同账号检测
	 */
	@RequestMapping(value = "/sameCheckAccount", method = RequestMethod.POST)
	public void sameCheckAccount(HttpServletRequest request, HttpServletResponse response) {
		
		JSONResult result = new JSONResult();
		String account = request.getParameter("account");
		User args = new User();
		args.setAccount(account);
		
		//ajax用户相同账号检测
		if(account!=null && !"".equals(account)) {
			List<User> check = this.userService.list(args);
			if(check.size()>0) {
				result.setStatus(1);
				result.setMessage("1");
				this.getPrintWriter(response, new JSONResult(1,new Object(),"已有相同的用户账号!"));
			} else {
				result.setStatus(0);
				result.setMessage("0");
				this.getPrintWriter(response, new JSONResult(0,new Object(),"没有相同账号!"));
			}
		}
	}
	
	/**
	 * ajax用户相同手机检测
	 */
	@RequestMapping(value = "/sameCheckMobileNo", method = RequestMethod.POST)
	public void sameCheckMobileNo(HttpServletRequest request, HttpServletResponse response) {

		JSONResult result = new JSONResult();
		String mobileNo = request.getParameter("mobileNo");
		User args = new User();
		args.setMobileNo(mobileNo);
		
		//ajax用户相同手机检测
		if(mobileNo!=null && !"".equals(mobileNo)) {
			List<User> check = this.userService.list(args);
			if(check.size()>0) {
				result.setStatus(1);
				result.setMessage("1");
				this.getPrintWriter(response, new JSONResult(1,new Object(),"已有相同的用户手机!"));
			} else {
				result.setStatus(0);
				result.setMessage("0");
				this.getPrintWriter(response, new JSONResult(0,new Object(),"没有相同手机!"));
			}
		}
	}
	
	/**
	 * 新增用户
	 * @throws Exception 
	 */
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public String insert(HttpServletRequest request, User user, RedirectAttributes attr) throws Exception {
		
		String path = "";//图片路径
		//处理图片
		if(user.getPath()!=null && !"".equals(user.getPath())) {
			String base64ImageStr = user.getPath();
			base64ImageStr = base64ImageStr.replaceFirst("data:(.+?);base64,", "");
			path = uploadService.save(Base64.decode(base64ImageStr), Long.parseLong(user.getOrganId()));
		}
		
		//session 获取userId
		Long userId = this.getAccountFromSession().getUserId();
		
		// 随机6位数作为MASK
		int mask=(int)(Math.random()*1000000);
		
		user.setPassword(Md5.md5(Md5.md5(user.getPassword())+String.valueOf(mask)));
		user.setMask(mask+"");
		user.setPath(path);
		
		// 调用接口执行新增
		// 角色串
		String roleIds = request.getParameter("roleIds");
		// 执行保存
		Calendar calendar = Calendar.getInstance();
		user.setCreater(userId);
		user.setCreatedTime(new Timestamp(calendar.getTimeInMillis()));
		int row = this.userService.save(user,roleIds);
		
		if (row >= 0) {
			attr.addFlashAttribute(ERROR_TITLE, "用户新增成功！");
		} else {
			attr.addFlashAttribute(ERROR_TITLE, "用户新增失败！");
		}
		return REDIRECT_LIST;
	}
	
	/**
	 * 跳转到用户修改页面
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(HttpServletRequest request, Model model, User user) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", user.getUserId());
		params.put("start", 0);
		params.put("size", 5);
		
		List<User> userList= this.userService.querypage(params);
		
		// 获取修改的用户信息
		model.addAttribute("user", userList.get(0));
		
		// 获取角色串
		UserRole args = new UserRole();
		args.setUserId(user.getUserId());
		List<UserRole> userRole = this.userRoleService.list(args);
		String roleIds = "";
		//拼接串
		for(int i=0;i<userRole.size();i++) {
			if(i+1>=userRole.size()) {
				roleIds = roleIds + userRole.get(i).getRoleId().toString();
			} else {
				roleIds = roleIds + userRole.get(i).getRoleId().toString() + ",";
			}
		}
		
		model.addAttribute("regexFlag", ConfigConsts.REGEX_FLAG);
		model.addAttribute("roleIds", roleIds);
		
		return "pages/user/user-edit";
	}
	
	/**
	 * 修改用户
	 * @throws Exception 
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(HttpServletRequest request, User user, RedirectAttributes attr) throws Exception {
		
		// session 获取userId
		Long userId = this.getAccountFromSession().getUserId();
		
		// 判断密码是否有修改
		if(!"******".equals(user.getPassword()) && user.getPassword() != null && !"".equals(user.getPassword())) {
			// 随机6位数作为MASK
			int mask=(int)(Math.random()*1000000);
			user.setPassword(Md5.md5(Md5.md5(user.getPassword())+String.valueOf(mask)));
			user.setMask(mask+"");
		}
		if("******".equals(user.getPassword())){
			user.setPassword(user.getEncryptionPwd());
		}
		
		//判断图片是否改变
		if("".equals(user.getPath()) || user.getPath() == null){
			user.setPath(user.getKeepPath());
		} else {
			String path = "";// 图片路径
			// 处理图片
			if(user.getPath()!=null && !"".equals(user.getPath())) {
				String base64ImageStr = user.getPath();
				base64ImageStr = base64ImageStr.replaceFirst("data:(.+?);base64,", "");
				path = uploadService.save(Base64.decode(base64ImageStr), Long.parseLong(user.getOrganId()));
			}
			user.setPath(path);
		}
			
		// 调用接口执行更新
		// 角色串
		String roleIds = request.getParameter("roleIds");
		// 执行保存
		user.setUpdator(userId);
		user.setUpdatedTime(new Timestamp(new Date().getTime()));
		int row = this.userService.updateUserInfo(user,roleIds);
		
		if (row >= 0) {
			attr.addFlashAttribute(ERROR_TITLE, "用户更新成功！");
		} else {
			attr.addFlashAttribute(ERROR_TITLE, "用户更新失败！");
		}
		return REDIRECT_LIST;
	}
	
	/**
	 * 查询用户工详情
	 */
	@RequestMapping(value = "/query")
	public String query(HttpServletRequest request, Model model, User user) {
		
		User args = new User();
		args.setUserId(user.getUserId());
		
		// 查询用户信息
		user = this.userService.get(args);
		model.addAttribute("user", user);
		
		// 获取角色串
		UserRole args2 = new UserRole();
		args2.setUserId(user.getUserId());
		List<UserRole> userRole = this.userRoleService.list(args2);
		String roleIds = "";
		// 拼接串
		for(int i=0;i<userRole.size();i++) {
			if(i+1>=userRole.size()) {
				roleIds = roleIds + userRole.get(i).getRoleId().toString();
			} else {
				roleIds = roleIds + userRole.get(i).getRoleId().toString() + ",";
			}
		}
		
		model.addAttribute("roleIds", roleIds);
		
		return "pages/user/user-query";
	}
}